import os
import sys
import time
from enum import Enum
from pywinauto.findwindows import ElementNotFoundError
import pyautogui
import pyperclip
import config
from ai_util import AiUtil
from my_log import my_log
from ui_kit import is_windows

class WechatPositionKey(Enum):
    tab_chat = "tab_chat"
    tab_contact = "tab_contact"
    tab_moment = "tab_moment"

class Wechat(object):

    positions = {}
    wechat_path = ""

    def __init__(self):
        self.__path = ""
        # 微信的主窗口对象
        self.__main_win = None
        # 微信输入框的对象
        self.__input_msg_box = None
        # 查询输入框对象
        self.__search_box = None
        # 微信默认显示的会话列表框
        self.__dia_list = None
        # 输入框的标题的button
        self.__input_title_btn = None
        # 右侧面板
        self.__right_panel = None

    def install(self, path):
        self.__path = path

    @classmethod
    def instance(cls, *args, **kwargs):
        if not hasattr(Wechat, "_instance"):
            Wechat._instance = Wechat()
        return Wechat._instance

    """
    获取用户控件，初始化各个参数
    :param username:
    :return:
    """
    def __init_elements(self):
        if is_windows():
            if not self.__path:
                raise Exception("微信exe路径不能为空！")
            if not self.__main_win:
                self.__main_win = Wechat.__get_main_win(self.__path)
            try:
                self.__main_win.set_focus()
            except ElementNotFoundError:
                raise Exception("核心窗口对象没有找到，请检测微信是否已经登录")
            if not self.__search_box:
                self.__search_box = self.__main_win.child_window(title='搜索', control_type="Edit").wrapper_object()
            # 获取Edit控件的值，判断是否为空
            if len(self.__search_box.get_value().strip()) > 0:
                # 如果正在搜索中，删除按钮会出现
                del_btn = self.__search_box.parent().children()[-1]
                del_btn.click_input()
            # ----1、尝试选择下拉控件----
            # if not self.__is_latest_user(username):
            #     self.__auto_by_list(username)
            #     # 等待右边的输入框的显示
            #     time.sleep(1)
            if not self.__input_msg_box:
                self.__input_msg_box = self.__main_win.child_window(title="输入", control_type="Edit").wrapper_object()
            if not self.__right_panel:
                # 根据元素位置来进行编程(参照inspect)
                self.__right_panel = self.__input_msg_box.parent().parent().parent().parent().parent().parent()
            # ----2、如果已经获取到输入框，则检查一下信息框是否存在----
            # if not self.__input_title_btn:
            #     # 如果还没有找到这个输入框的标题控件
            #     item_list = self.__right_panel.children()
            #     if len(item_list) > 0:
            #         # 从右侧面板的第一个控件(右侧顶部面板)开始查找(参照inspect)
            #         item_list = item_list[0].descendants(title=username, control_type="Button")
            #         if len(item_list) == 0:
            #             raise Exception("没有找到当前用户的对话框！")
            #         self.__input_title_btn = item_list[0]
            # if self.__input_title_btn.element_info.name != username:
            #     # 如果输入框的标题不是当前用户
            #     raise Exception("没有找到当前用户的对话框！")

    def open_wechat(self):
        if is_windows():
            pyautogui.hotkey("win", "d")
            cmd = self.wechat_path = ""
            file = os.popen(cmd)
            file.close()
            time.sleep(2)
        else:
            pyautogui.hotkey("command", "space")

    @staticmethod
    def setup_position():
        Wechat.setup_image_position(WechatPositionKey.tab_chat, config.wechat_tab_chat_image_path)
        Wechat.setup_image_position(WechatPositionKey.tab_contact, config.wechat_tab_contact_image_path)
        Wechat.setup_image_position(WechatPositionKey.tab_moment, config.wechat_tab_moment_image_path)

    @staticmethod
    def setup_image_position(key, image_path):
        try:
            # image:图片路径
            # confidence:定位精度，默认是0.8
            # count:定位到的图片数量，默认是1
            point = pyautogui.locateCenterOnScreen(image=image_path, confidence=0.5)
            my_log.debug(f"setup_image_position {key} = {point}")
            Wechat.save_position(key, point)
        except:
            my_log.error(f"setup_image_position setup error, {key}")

    @staticmethod
    def save_position(key, point):
        positions = Wechat.instance().positions
        positions[key] = point

    # 目标图片需要一定时间才会出现，那么如何使得查找图片的函数（pyautogui.locateCenterOnScreen）一直运行？
    # # 该方法用于获取目标图像所在位置，只要没找到图像就一直找
    # def get_position(word):
    #     up_left = None
    #     while up_left == None:
    #         up_left = pyautogui.locateCenterOnScreen('../目标路径/{}.png'.format(word), confidence=0.9)
    #     return up_left



    @staticmethod
    def batch_send_message(users, msg, delay_time=1):
        for user in users:
            Wechat.send_message(user, msg, delay_time)

    @staticmethod
    def send_message(target, msg, delay_time=2):
        """
        实现原理：1、通过打开微信的快捷键ctrl+alt+w,打开微信窗口
                2、通过搜索快捷键ctrl+f,打开搜索窗口
                3、通过ctrl+v快捷键实现输入功能
                4、通过ctrl+enter快捷键实现搜索or发送功能
        :param target: 发送目标
        :param msg: 需要发送的消息
        :param delay_time: 延迟时间 默认x秒
        :return:无返回值
        """
        try:
            is_show_window = False
            ctrl = "ctrl"
            alt = "alt"
            if not is_windows():
                ctrl = "command"
                alt = "ctrl"
                screenshot = pyautogui.screenshot(region=(0, 0, 150, 30))
                # 保存截图
                screenshot.save(config.screenshot_save_path)
                result = AiUtil.find_text(config.screenshot_save_path, search_texts=["微信", "徽信"])
                if result is None:
                    # print(f"find_text={result}")
                    is_show_window = True

            # 清空剪切板并将目标写入到剪切板
            # pyperclip.copy("")
            pyperclip.copy(target)
            if is_show_window:
                # 打开微信窗口
                pyautogui.hotkey(ctrl, alt, "w")
                time.sleep(delay_time)
            # 使用快捷键ctrl+f定位到微信搜索栏
            pyautogui.hotkey(ctrl, "f")
            time.sleep(delay_time)
            # 使用快捷键ctrl+v将目标粘贴到微信搜索栏，微信将自动搜索
            pyautogui.hotkey(ctrl, "v")
            time.sleep(delay_time)
            # 按回车键打开搜索出的目标
            pyautogui.press("enter")
            time.sleep(delay_time)
            # 清空剪切板并将未点检信息写入到剪切板
            # pyperclip.copy("")
            pyperclip.copy(msg)
            # 使用快捷键ctrl+v将信息粘贴到微信输入框，按回车发送消息
            pyautogui.hotkey(ctrl, "v")
            time.sleep(delay_time)
            pyautogui.press("enter")
            # log
            my_log.info(f"发送微信消息 target={target}, msg={msg}")

        except Exception as ex:
            my_log.error("发送微信消息出现异常: " + str(ex))
            sys.exit(0)